﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using SnmpForm.APConfig;
using SnmpForm.DbWrapper.DbDataTypes;

namespace SnmpForm.FaultDetect
{
    public partial class FrmFaultDetect : Form
    {
        private string m_nIndex = "";
        private int m_nFaultStatus = 1;
        private int m_nApId = -1;
        private int m_strfaultType = -1;

        Dictionary<int, DbWrapper.DbDataTypes.FailureInfo> mapFaultInfo = 
            new Dictionary<int,DbWrapper.DbDataTypes.FailureInfo>();
        public FrmFaultDetect()
        {
            InitializeComponent();
        }

        private void FrmFaultDetect_Load(object sender, EventArgs e)
        {
            updateTreeViewAp();

            //装载错误编号信息
            List<DbWrapper.DbDataTypes.FailureInfo> listFault =
                DbWrapper.SQLDataOperate.Instance.GetFailureInfo(0);
            mapFaultInfo.Clear();
            foreach (DbWrapper.DbDataTypes.FailureInfo info in listFault)
            {
                mapFaultInfo[info.id] = info;
            }

            comboBoxFaultStatus.DataSource =
                FAULT_DEFINE_DATA.FAULT_STATUS_TYPE.Clone();

            listViewFaultAp.View = View.Details;
            listViewFaultAp.FullRowSelect = true;
            listViewFaultAp.Columns.Add("编号");
            listViewFaultAp.Columns.Add("AP标志", 100);
            listViewFaultAp.Columns.Add("托管IP", 120);
            listViewFaultAp.Columns.Add("房间号", 60);
            listViewFaultAp.Columns.Add("故障描述", 300);

            ReloadViewFaultAp();

            comboBoxFaultType.DataSource =
                FAULT_DEFINE_DATA.FAULT_NAME_TYPE.Clone();
            dataGridViewFaultInfo.ColumnCount = 6;
            dataGridViewFaultInfo.Columns[0].Name = "编号";
            dataGridViewFaultInfo.Columns[1].Name = "故障类型";
            dataGridViewFaultInfo.Columns[2].Name = "故障级别";
            dataGridViewFaultInfo.Columns[3].Name = "故障检测时间";
            dataGridViewFaultInfo.Columns[4].Name = "故障描述";
            dataGridViewFaultInfo.Columns[5].Name = "故障处理";
        }

        private bool updateTreeViewAp()
        {
            List<BusinessWrapper.Types.GroupInfo> listGroupInfo =
                BusinessWrapper.User.Instance.GetGroup();
            listGroupInfo.Sort((left, right) =>
            {
                int bLess = 0;
                try
                {
                    int nLeft = Convert.ToInt32(left.name);
                    int nRight = Convert.ToInt32(right.name);
                    bLess = nLeft - nRight;
                }
                catch (Exception ex)
                {
                    bLess = left.name.CompareTo(right.name);
                    Console.WriteLine(ex.Message);
                }
                return bLess;
            }
            );
            treeViewAp.Nodes.Clear();
            TreeNode nodeRoot = new TreeNode();
            nodeRoot.Text = "楼层信息";
            treeViewAp.Nodes.Add(nodeRoot);

            for (int nIndex = 0; nIndex < listGroupInfo.Count; nIndex++)
            {
                TreeNode node = new TreeNode();
                if (listGroupInfo[nIndex].name.Equals("unknown"))
                {
                    node.Text = "未归属楼层AP";
                    node.Name = listGroupInfo[nIndex].name;
                    nodeRoot.Nodes.Insert(0, node);
                }
                else
                {
                    node.Text = listGroupInfo[nIndex].name;
                    node.Name = listGroupInfo[nIndex].name;
                    nodeRoot.Nodes.Add(node);
                }
            }
            //默认展开
            treeViewAp.ExpandAll();
            return true;
        }

        public void ReloadViewFaultAp(string strIP = "",string strMark = "")
        {
            listViewFaultAp.Items.Clear();
            Dictionary<int, HashSet<int>> mapFaultAp = null;
            if (m_nFaultStatus == 0)
            {//当前故障
                mapFaultAp = FaultDetect.DetectData.Instance.Get();
            }
            else if (m_nFaultStatus == 1)
            {//历史故障
                mapFaultAp = BusinessWrapper.User.Instance.GetFaultApList(m_nIndex,strIP,strMark);
            }
            foreach (KeyValuePair<int, HashSet<int>> pair in mapFaultAp)
            {
                if (pair.Value.Count > 0)
                {
                    int apid = pair.Key;
                    BusinessWrapper.Ap ap = BusinessWrapper.User.Instance.GetAp(apid);
                    if (ap != null)
                    {
                        if ( (ap.GetInfo().floorid == m_nIndex || m_nIndex.Equals("")) &&
                            (strIP == null || strIP == "" || ap.GetInfo().manage_ip == strIP) &&
                            (strMark == null || strMark == "" || ap.GetInfo().mark.Contains(strMark)))
                        {
                            string strFault = "";
                            foreach (int faultid in pair.Value)
                            {
                                strFault += mapFaultInfo[faultid].failurename;
                                strFault += "; ";
                            }

                            ListViewItem lvi = new ListViewItem();
                            lvi.Text = apid.ToString();
                            lvi.SubItems.Add(ap.GetInfo().mark);
                            lvi.SubItems.Add(ap.GetInfo().manage_ip);
                            lvi.SubItems.Add(ap.GetInfo().roomid);
                            lvi.SubItems.Add(strFault);
                            listViewFaultAp.Items.Add(lvi);
                        }
                    }
                }
            }
        }

        public void ReloadViewFaultInfo(string date = "")
        {
            int count = 1;
            
            DataGridViewRowCollection rows = this.dataGridViewFaultInfo.Rows;
            rows.Clear();

            List<FailureApInfo> failureInfoList =
                BusinessWrapper.User.Instance.GetApFaultList(m_nApId,m_strfaultType,date);
            if (failureInfoList == null)
                return;
            foreach (FailureApInfo failureInfo in failureInfoList)
            {
                string[] row = { count.ToString(), failureInfo.failurename,failureInfo.level.ToString(),
                                    failureInfo.createtime,failureInfo.failuredescription, failureInfo.description};
                rows.Add(row);
                count++;

            }
        }

        private void treeViewAp_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                m_nIndex = treeViewAp.SelectedNode.Name;
            }
            catch
            {
            }
            ReloadViewFaultAp();
        }

        private void listViewFaultAp_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewFaultAp.SelectedItems.Count > 0)
            {
                ListViewItem item = listViewFaultAp.SelectedItems[0];
                m_nApId = Convert.ToInt32(item.Text);
                BusinessWrapper.Ap ap = BusinessWrapper.User.Instance.GetAp(m_nApId);
                if (ap == null)
                    ReloadViewFaultAp();
                else
                {
                    //显示运行状态
                    ucApStatus1.InitWith(ap);
                    ucApStatus1.Enabled = true;

                    ReloadViewFaultInfo();
                }
            }
            else
            {
                ucApStatus1.cleanApStatusView();
                ucApStatus1.Enabled = false;
            }
        }

        private void buttonFaultList_Click(object sender, EventArgs e)
        {
            string ipCondition = null, markCondition = null;

            byte[] ip = ipAddressControl.GetAddressBytes();
            IPAddress addrIP = new IPAddress(ip);
            if (!addrIP.Equals(ApSearch.IPAddressExtend.ZeroAddress))
            {
                ipCondition = addrIP.ToString();
            }
            
            if(textBoxMark.Text.Length != 0)
            {
                markCondition = textBoxMark.Text;
            }

            ReloadViewFaultAp(ipCondition, markCondition);
        }

        private void buttonFaultInfo_Click(object sender, EventArgs e)
        {
            string strDatetime = dateTimePicker.Value.ToString("yyyy-MM-dd HH:mm:ss");
            ReloadViewFaultInfo(strDatetime);
        }

        private void comboBoxFaultStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            ApConfigItem item = null;
            item = (ApConfigItem)comboBoxFaultStatus.SelectedValue;
            int type = (int)item.Value;
            switch (type)
            {
                case 0:
                    m_nFaultStatus = 0;
                    break;
                case 1:
                    m_nFaultStatus = 1;
                    break;
                default:
                    break;
            }
            ReloadViewFaultAp();
        }

        private void comboBoxFaultType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ApConfigItem item = null;
            item = (ApConfigItem)comboBoxFaultType.SelectedValue;
            int type = (int)item.Value;
            m_strfaultType = type;
            ReloadViewFaultInfo();
        }

        private void ToolStripMenuItemRefresh_Click(object sender, EventArgs e)
        {
            updateTreeViewAp();
        }

    }
}
